package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.product.config.AppMinioProperties;
import com.atguigu.gmall.product.service.FileUploadService;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService{


    @Autowired
    MinioClient minioClient;

    @Autowired
    AppMinioProperties appMinioProperties;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @Override
    public String upload(MultipartFile file) {
        String url = appMinioProperties.getEndpoint()+appMinioProperties.getBucket()+"/";
        try {
            InputStream inputStream = file.getInputStream();
            String name = UUID.randomUUID().toString().replace("-","")+"_"+ file.getName();
            url+=name;
            String contentType = file.getContentType();
            PutObjectOptions putObjectOptions = new PutObjectOptions(-1, 5*1024*1024);
            putObjectOptions.setContentType(contentType);
            minioClient.putObject(appMinioProperties.getBucket(),
                    name,
                    inputStream,
                    putObjectOptions);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return url;
    }
}
